<template>
	<view>
		<!-- 顶部栏：项目选择 + 搜索框 -->
		<view class="map-header">
			<!-- 项目选择 -->
			<view class="project-select" @click="showProjectPicker = true">
				<text>{{ selectedProjectName }}</text>
				<uni-icons type="arrowdown" size="16" color="#333" />
			</view>

			<!-- 项目选择器弹窗 -->
			<view v-if="showProjectPicker" class="picker-popup" @click.self="showProjectPicker = false">
				<view class="picker-options">
					<view v-for="(item, index) in projects" :key="index" class="picker-option"
						@click="selectProject(item)">
						{{ item.text }}
					</view>
				</view>
			</view>


			<!-- 搜索框 -->
			<view class="search-box">
				<uni-icons type="search" size="20" color="#999" />
				<input type="text" v-model="searchKeyword" placeholder="搜索设备ID/名称" placeholder-style="color:#ccc"
					@input="handleInput" />
			</view>
		</view>

		<map v-if="showMap" style="width: 100%; height: 60vh;" :latitude="location.lat" :longitude="location.lng"
			:markers="covers" @markertap="gotoDetail">
		</map>

		<!-- 搜索结果文字列表 -->
		<scroll-view scroll-y style="height: 40vh; background: #fff;">
			<view v-for="(item, index) in covers" :key="index" class="result-item"
				@click="gotoDetail({ detail: { markerId: index } })">
				<view class="result-title">{{ item.code }}</view>
				<view class="result-sub">{{ item.latitude }}, {{ item.longitude }}</view>
			</view>
		</scroll-view>

		<!-- <view class="home-icon-r">
			<view class="home-icon">
				<image src="../../static/img/home-con2.png" mode=""></image>
				<view>工单</view>
			</view>
			<view class="home-icon">
				<image src="../../static/img/home-con1.png" mode=""></image>
				<view>扫码</view>
			</view>
			<view class="home-icon">
				<image src="../../static/img/home-con3.png" mode=""></image>
				<view>刷新</view>
			</view>
		</view> -->
		<uniFab ref='fab' :content="content" @trigger="trigger"></uniFab>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import uniFab from '@/components/uni-fab'
	export default {
		data() {
			return {
				statusBarHeight: 0,
				selectedProject: '骊山项目',
				showProjectPicker: false,
				projects: ['骊山项目', '华山项目'],
				selectedProjectId: null,
				selectedProjectName: '',
				searchKeyword: '',
				inputTimer: null,
				showMap: false,
				id: 0, // 使用 marker点击事件 需要填写id
				title: 'map',
				latitude: '', //39.909
				longitude: '', //116.39742
				covers: [],
				content: [{
					iconPath: 'https://yun.qiongtuyule.com/static/img/home-con02.png',
					selectedIconPath: 'https://yun.qiongtuyule.com/static/img/home-con2.png',
					text: '添加设备',
					active: false
				}, {
					iconPath: 'https://yun.qiongtuyule.com/static/img/home-con01.png',
					selectedIconPath: 'https://yun.qiongtuyule.com/static/img/home-con1.png',
					text: '扫码',
					active: false
				}, {
					iconPath: 'https://yun.qiongtuyule.com/static/img/home-con03.png',
					selectedIconPath: 'https://yun.qiongtuyule.com/static/img/home-con3.png',
					text: '刷新',
					active: false
				}],
				mySocket: null,
				timer: null,
				lockReconnect: false,
				isSocketConnected: false,
				heartBeatTime: 0,
				serverTimeoutObj: null,
				siteTimer: null, //获取站点列表的定时器
			}
		},
		components: {
			uniFab
		},
		computed: {
			...mapState([
				"userInfo", "location"
			]),
		},
		onShow() {

			// this.getStatusBarHeight();
			if (this.userInfo.token == undefined) {
				this.loginOut();
				return
			} else {
				// this.getIndexSite();
				this.getProjects();
				if (this.siteTimer == null) {
					this.siteTimer = setInterval(() => {
						// this.getIndexSite();
						this.getProjects();
					}, 60000)
				}
			}
			this.authorization(); //获取 位置授权
		},
		onHide() {
			this.$refs.fab.close();
			if (this.siteTimer != null) {
				clearInterval(this.siteTimer)
				this.siteTimer = null
			}
		},
		methods: {
			handleInput() {
				clearTimeout(this.inputTimer)
				this.inputTimer = setTimeout(() => {
					this.getIndexSite()
				}, 300) // 300ms防抖
			},
			getStatusBarHeight() {
				const systemInfo = uni.getSystemInfoSync();
				this.statusBarHeight = systemInfo.statusBarHeight;
			},
			async getProjects() {
				let res = await this.$lib.$http.post({
					url: this.$lib.$urlMap.siteTree3,
					data: {}
				})
				if (res.code === 1) {
					const allProject = {
						value: 0,
						text: '全部项目'
					};
					this.projects = [allProject, ...res.data];
					if (this.projects.length > 0) {
						this.selectedProjectId = this.projects[0].value
						this.selectedProjectName = this.projects[0].text
						this.getIndexSite()
					}
				}
			},

			selectProject(project) {
				this.selectedProjectId = project.value
				this.selectedProjectName = project.text
				this.showProjectPicker = false
				this.getIndexSite()
			},
			filterMarkers() {
				const keyword = this.searchKeyword.trim();
				this.covers = this.allMarkers.filter(marker => {
					const matchProject = marker.project === this.selectedProject;
					const matchKeyword =
						keyword === '' ||
						marker.code.includes(keyword) ||
						marker.id.toString().includes(keyword);
					return matchProject && matchKeyword;
				});
			},
			async authorization() {
				try {
					// #ifdef MP-WEIXIN
					await this.getPosterLocation();
					// #endif
				} catch (error) {
					// console.log(error)
					uni.showModal({
						title: '温馨提示',
						content: '获取权限失败，请将位置信息设置为【使用小程序时允许】！',
						success: (res) => {
							if (res.confirm) {
								// #ifdef MP-WEIXIN
								this.handleOpenSettng();
								// #endif
							}
						}
					});
					return;
				}
			},
			handleOpenSettng() {
				// console.log("获取用户授权");
				// #ifdef MP-WEIXIN
				wx.openSetting({
					success: (res) => {
						if (res.authSetting["scope.userLocation"]) { // 用户同意授权
							// console.log("用户同意授权");
							this.authorization();
						}
					}
				})
				// #endif
			},
			// #ifdef MP-WEIXIN
			//获取定位
			getPosterLocation() {
				let that = this
				return new Promise((resolve, reject) => {
					uni.getLocation({
						type: 'gcj02',
						success: function(res) {
							// console.log('当前位置的经度：' + res.longitude);
							// console.log('当前位置的纬度：' + res.latitude);
							let data = {
								latitude: res.latitude,
								longitude: res.longitude
							}
							that.handleLocationChange(data)
							resolve();
						},
						fail: (err) => {
							// console.log('微信端获取当前位置失败', err);
							reject();
						}
					});
				})
			},
			// #endif
			handleLocationChange(res) {
				let info = {
					lat: res.latitude,
					lng: res.longitude
				}
				this.$store.commit('SETUSERlOCATION', info)
			},
			loginOut() {
				this.$lib.$store.commit('clearUserInfo')
				uni.reLaunch({
					url: '/pages/login/index'
				})
			},
			trigger(e) {
				let that = this
				if (e.index == 0) {
					uni.navigateTo({
						url: '/pages/workOrder/createDevice'
					})
				} else if (e.index == 1) {
					// 只允许通过相机扫码
					uni.scanCode({
						onlyFromCamera: true,
						success: function(res) {
							let code = res.result;
							uni.navigateTo({
								url: '/pages/workOrder/createDevice?code=' + code
							})
						}
					});
				} else if (e.index == 2) {
					uni.showLoading()
					this.getIndexSite();
				}
			},
			gotoDetail(e) {
				console.log(this.covers)
				uni.openLocation({
					latitude: Number(this.covers[e.detail.markerId].latitude), // 终点纬度
					longitude: Number(this.covers[e.detail.markerId].longitude), // 终点经度
					name: this.covers[e.detail.markerId].code,
					address: this.covers[e.detail.markerId].address,
					success: () => console.log('已打开系统地图'),
					fail: err => console.log('打开失败', err)
				});

				// uni.navigateTo({
				// 	url:'/pages/shouye/maintain?code=' + this.covers[e.detail.markerId].code
				// })
			},
			async getIndexSite() {
				let res = await this.$lib.$http.post({
					url: this.$lib.$urlMap.deviceList,
					data: {
						project_id: this.selectedProjectId,
						keyword: this.searchKeyword.trim()
					},
					needLogin: true
				})
				if (res.code == 1) {
					let items = res.data;
					this.covers = []
					for (let i = 0, leng = items.length; i < leng; i++) {
						const item = items[i]
						if (item.lnglat != '') {
							let site = {
								id: i,
								// id: Number(item.code),
								code: item.code,
								latitude: item.lnglat.split(',')[1],
								longitude: item.lnglat.split(',')[0],
								iconPath: 'https://yun.qiongtuyule.com/static/img/location.png',
								width: 20,
								height: 20
							}
							this.covers.push(site)
							console.log(this.covers)
						}
					}
					this.showMap = true
					uni.hideLoading()
				} else {
					uni.hideLoading()
				}
			},
		}
	}
</script>

<style>
	.result-item {
		padding: 20rpx;
		border-bottom: 1px solid #eee;
	}

	.result-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
	}

	.result-sub {
		font-size: 26rpx;
		color: #999;
		margin-top: 6rpx;
	}


	.map-header {
		background-color: #dfe5f0;
		padding: 60rpx 20rpx 20rpx 20rpx;
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.project-select {
		display: flex;
		align-items: center;
		font-size: 34rpx;
		font-weight: bold;
		color: #000;
		padding-top: 32rpx;
	}

	.picker-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.3);
		z-index: 99;
	}

	.picker-options {
		background: #fff;
		margin: 200rpx 60rpx 0;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.picker-option {
		padding: 30rpx;
		border-bottom: 1rpx solid #eee;
		text-align: center;
		font-size: 30rpx;
		color: #333;
	}

	.picker-option:last-child {
		border-bottom: none;
	}


	.search-box {
		background-color: #fff;
		border-radius: 40rpx;
		padding: 10rpx 20rpx;
		display: flex;
		align-items: center;
		margin-top: 20rpx;
	}

	.search-box uni-icons {
		margin-right: 10rpx;
	}

	.search-box input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}

	.uni-fab__content--other-platform {
		box-shadow: none !important;
	}

	.home-icon-r {
		position: fixed;
		z-index: 111111111111111111;
		right: 6%;
		bottom: 4%;
	}

	.home-icon {
		background: #4d71ff;
		display: flex;
		flex-direction: column;
		align-items: center;
		color: #fff;
		font-size: 12px;
		width: 55px;
		height: 55px;
		line-height: 12px;
		border-radius: 52px;
		margin-bottom: 12px;
	}

	.home-icon image {
		width: 30px;
		height: 30px;
		margin-top: 2px;
	}
</style>